package com.hup.utils.io.batch.function;

import com.hup.utils.io.batch.BaseBatch;
import com.hup.utils.io.batch.function.ScQueryStateAll.ScQueryService;
import lombok.ToString;
import lombok.extern.log4j.Log4j2;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author hugan
 * @date 2020/3/31
 */
@Log4j2
public class ScQueryStateAll implements BaseBatch<ArrayList<ScQueryService>> {

    @Override
    public String cmd() {
        return "sc query state= all";
    }

    @Override
    public String desc() {
        return "查询系统服务列表[服务名,显示名]";
    }

    @Override
    public ArrayList<ScQueryService> parse(ArrayList<String> lstResp) {
        ArrayList<ScQueryService> res = new ArrayList<>();
        if (lstResp.isEmpty()) return res;

        Iterator<String> it = lstResp.iterator();
        while (it.hasNext()) {
            String line1 = it.next();
            if (!line1.startsWith("SERVICE_NAME")) continue;
            String line2 = it.next();

            int iSt = line1.lastIndexOf(": ") + 2;
            String serviceName = line1.substring(iSt);
            iSt = line2.lastIndexOf(": ") + 2;
            String displayName = line2.substring(iSt);
            res.add(new ScQueryService(serviceName, displayName));
        }
        return res;
    }

    /**
     * SERVICE_NAME: AJRouter
     * DISPLAY_NAME: AllJoyn Router Service
     * TYPE               : 20  WIN32_SHARE_PROCESS
     * STATE              : 1  STOPPED
     * WIN32_EXIT_CODE    : 1077  (0x435)
     * SERVICE_EXIT_CODE  : 0  (0x0)
     * CHECKPOINT         : 0x0
     * WAIT_HINT          : 0x0
     */
    @ToString
    public static class ScQueryService {
        public final String serviceName;
        public final String displayName;

        public ScQueryService(String serviceName, String displayName) {
            this.serviceName = serviceName;
            this.displayName = displayName;
        }
    }

}
